package com.ljy.my_study.java.thread.notifywait;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author lijunying
 * @date 2021/1/4 8:28
 */
public class TestMain {

    public static void main(String[] args) throws InterruptedException {
        Queue<Integer> queue=new LinkedList<>();

        Runnable runnable1=new Runnable() {
            @Override
            public void run() {
                try {
                    Integer value;
                    while(true){
                        if((value=queue.poll())==null){
                            synchronized (queue) {
                                System.out.println("thread name:" + Thread.currentThread().getName() + " wait.");
                                queue.wait();
                            }
                        }else{
                            System.out.println("thread name:"+Thread.currentThread().getName()+",value:"+value);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable runnable2=new Runnable() {
            @Override
            public void run() {
                offerQueue(queue,1);
                offerQueue(queue,2);

            }
        };

        Runnable runnable3=new Runnable() {
            @Override
            public void run() {
                offerQueue(queue,3);
                offerQueue(queue,4);
                offerQueue(queue,5);
            }
        };

        new Thread(runnable1).start();
        new Thread(runnable2).start();
        new Thread(runnable3).start();
    }

    private static void offerQueue(Queue<Integer> queue,Integer value){
        boolean isEmpty=queue.isEmpty();
        queue.offer(value);
        if(isEmpty){
            synchronized (queue){
                System.out.println("线程"+Thread.currentThread().getName()+" 执行 notify start");
                queue.notify();
                System.out.println("线程"+Thread.currentThread().getName()+" 执行 notify end");
            }
        }
    }
}
